/*  
 *  ------ [802_02] - send packets -------- 
 *  
 *  Explanation: This program shows how to send packets to a gateway
 *  indicating the MAC address of the receiving XBee module 
 *  
 *  Copyright (C) 2012 Libelium Comunicaciones Distribuidas S.L. 
 *  http://www.libelium.com 
 *  
 *  This program is free software: you can redistribute it and/or modify 
 *  it under the terms of the GNU General Public License as published by 
 *  the Free Software Foundation, either version 3 of the License, or 
 *  (at your option) any later version. 
 *  
 *  This program is distributed in the hope that it will be useful, 
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 *  GNU General Public License for more details. 
 *  
 *  You should have received a copy of the GNU General Public License 
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 *  
 *  Version:           0.1 
 *  Design:            David Gascón 
 *  Implementation:    Yuri Carmona
 */
 
#include <MakeSureXBee802.h>
#include <MakeSureFrame.h>

//Pointer to an XBee packet structure 
packetXBee* packet; 

// Destination MAC address
char* MAC_ADDRESS="0013A20040A5CE98";
char* MAC_LOW="40A5CE98";
char * MoteID="MakeSure_XBEE";
String s;
void setup()
{
  // init USB port
  //USB.ON();
  //USB.println(F("802_2 example"));
	Serial.begin(9600);
	Serial.println("Serial Port Started");
  // init XBee
  xbee802.ON();
  
}


void loop()
{
  ///////////////////////////////////////////
  // 1. Create ASCII frame
  ///////////////////////////////////////////  

  // create new frame
  frame.createFrame(ASCII,MAC_LOW,MoteID);  
 Serial.println("Frame Created");
  // add frame fields
  frame.addSensor(SENSOR_STR, "XBee frame");
  Serial.println("Added Sensor");
  //frame.addSensor(SENSOR_BAT, PWR.getBatteryLevel()); 
  

  ///////////////////////////////////////////
  // 2. Send packet
  ///////////////////////////////////////////  

  // set parameters to packet:
  packet=(packetXBee*) calloc(1,sizeof(packetXBee)); // Memory allocation
  packet->mode=UNICAST; // Choose transmission mode: UNICAST or BROADCAST
  Serial.println("Packet Created");
  // set destination XBee parameters to packet
  xbee802.setDestinationParams( packet, MAC_ADDRESS, frame.buffer, frame.length, MAC_TYPE); 
  Serial.println("Packet Finalized");
  /*utoa(packet,s,10);*/
  s=String(packet->data);
  Serial.println(s);
  // send XBee packet
  xbee802.sendXBee(packet);
  Serial.println("Packet Sent");
  // check TX flag
  if( xbee802.error_TX == 0 )
  {
    //USB.println(F("ok"));
	  Serial.println("ok");
  }
  else 
  {
   Serial.println("Error");
  }
  
  // free variables
  free(packet);
  packet=NULL;

  // wait for five seconds
  delay(5000);
}



